package com.example.miscontactos;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.widget.Toast;

public class CheckInternetConnection extends BroadcastReceiver
{
	private SharedPreferences preferencias;
	private String ESTA_INTERNET_ON = "esta_internet_on";

	@Override
	public void onReceive(Context context, Intent intent) 
	{
		preferencias = PreferenceManager.getDefaultSharedPreferences(context);
		SharedPreferences.Editor editor = preferencias.edit();
	    Toast toast = null;
	    CharSequence message = "";
	    if (isOnLine(context)) 
	    {
	    	message = (CharSequence)context.getResources().getString(R.string.internet_conection);
	    	toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
		    editor.putBoolean(ESTA_INTERNET_ON, true);
		    editor.commit();		
	    }
	    else
	    {
	    	message = (CharSequence)context.getResources().getString(R.string.no_internet_conection);
	    	toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
	    	editor.putBoolean(ESTA_INTERNET_ON, false);
		    editor.commit();
	    }
	    toast.show();
	}
	
	private Boolean isOnLine(Context c) 
	{
	    ConnectivityManager connMgr = (ConnectivityManager) c
	            .getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
	    return (networkInfo != null && networkInfo.isConnected());

	}
	
}
